package com.qf.studentmanager.service;

import com.qf.studentmanager.config.DBConfig;
import com.qf.studentmanager.dao.StudentDao;
import com.qf.studentmanager.model.RespPageBean;
import com.qf.studentmanager.model.Student;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class StudentService {
    StudentDao studentDao = new StudentDao();

    public RespPageBean getAllStudentBypage(String page, String rows, String sort, String order, String gid,String cid) {
        if (page == null){
            page = "1";
        }
        if (rows == null){
            rows = "10";
        }
        if (sort == null){
            sort = "cid";
        }
        if (order == null){
            order ="asc";
        }
        RespPageBean respPageBean = new RespPageBean();
        Long total = studentDao.getTotal(gid,cid);//根据年级和班级id查，

        int p = Integer.parseInt(page);
        int r = Integer.parseInt(rows);
        List<Student> list = studentDao.getClazzByPage((p-1)* r,r,sort,order,gid,cid);

        respPageBean.setTotal(total);
        respPageBean.setRows(list);
        return respPageBean;
    }

    public Integer addStudent(Student student) {
        Student stu= studentDao.getStudentByNumber(student.getNumber());
        try {
            if (stu != null){
                return   -2; //根据学号查，学生重复了。
            }else {
                Integer i =studentDao.addStudent(student);
                return i;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public Integer deleteStudents(String[] sids) {
        return studentDao.deleteStudentBySids(sids);
    }

    public Integer updateStudents(Student student) {
        Connection connection = DBConfig.getConnection();
        try {
            connection.setAutoCommit(false);
            //根据number先把要修改用学生删除，然后再添加
            Integer r1 = studentDao.deleteStudentByNumber(student.getNumber());
            //现在添加
           Integer r2 = studentDao.addStudent(student);
            connection.commit();
            if (r1 == r2){
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return -1;
    }
}
